package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;
import com.atguigu.gulimall.common.utils.R;
import com.atguigu.gulimall.product.entity.SkuImagesEntity;
import com.atguigu.gulimall.product.entity.SpuInfoDescEntity;
import com.atguigu.gulimall.product.feign.SecKillFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.SecKillInfoVo;
import com.atguigu.gulimall.product.vo.SkuItemVo;
import com.atguigu.gulimall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.atguigu.gulimall.product.dao.SkuInfoDao;
import com.atguigu.gulimall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SecKillFeignService secKillFeignService;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ThreadPoolExecutor poolExecutor;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> wapper = new QueryWrapper<SkuInfoEntity>();

        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }

        String catelogId = (String) params.get("catelogId");
        if (StringUtils.isNotEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            wapper.eq("catalog_id", catelogId);
        }

        String brandId = (String) params.get("brandId");
        if (StringUtils.isNotEmpty(key) && !"0".equalsIgnoreCase(brandId)) {
            wapper.eq("brand_id", brandId);
        }

        String min = (String) params.get("min");
        if (StringUtils.isNotEmpty(min)) {
            try {
                BigDecimal minPrice = new BigDecimal(min);
                if (minPrice.compareTo(new BigDecimal("0")) == 1) {
                    wapper.ge("price", min);
                }

            } catch (Exception e) {

            }
        }

        String max = (String) params.get("max");
        if (StringUtils.isNotEmpty(max)) {
            try {
                BigDecimal maxPrice = new BigDecimal(max);
                if (maxPrice.compareTo(new BigDecimal("0")) == 1) {
                    wapper.le("price", max);
                }
            } catch (Exception e) {

            }
        }

        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                wapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkuBySpuId(Long spuId) {
        List<SkuInfoEntity> entities = this.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        return entities;
    }

    //  得到单个商品数据
    @Override
    public SkuItemVo item(Long skuId) {

        // 使用异步编排优化

        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> infoFutrue = CompletableFuture.supplyAsync(() -> {
            // 1. sku基本信息获取
            SkuInfoEntity skuInfoEntity = baseMapper.selectById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, poolExecutor);

        // 任务 3 ，4 ，5 都需要任务 1 完成之后进行
        CompletableFuture<Void> descFutrue = infoFutrue.thenAcceptAsync((skuInfoEntity) -> {
            // 3. spu介绍
            Long spuId = skuInfoEntity.getSpuId();
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(spuId);
            skuItemVo.setDesc(spuInfoDescEntity);
        }, poolExecutor);

        CompletableFuture<Void> saleFutrue = infoFutrue.thenAcceptAsync((skuInfoEntity -> {
            // 4. spu销售属性组合
            List<SkuItemVo.SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(skuInfoEntity.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }), poolExecutor);

        CompletableFuture<Void> attrGroupFrture = infoFutrue.thenAcceptAsync((skuInfoEntity -> {
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(skuInfoEntity.getSpuId(), skuInfoEntity.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }), poolExecutor);

        CompletableFuture<Void> imageFrture = CompletableFuture.runAsync(() -> {
            // 2. sku图片信息
            List<SkuImagesEntity> images = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, poolExecutor);

        //查询商品是否参与秒杀活动
        CompletableFuture<Void> killFutrue = infoFutrue.thenAcceptAsync((skuInfoEntity -> {
            R killInfo = secKillFeignService.getSkuSecKillInfo(skuId);
            SecKillInfoVo secKillInfoVo = (SecKillInfoVo) killInfo.getData("data", new TypeReference<SecKillInfoVo>() {
            });
            System.out.println("seckillInfoVo:"+secKillInfoVo.getEndTime());
            skuItemVo.setSecKillInfoVo(secKillInfoVo);
            skuItemVo.setStartTimeString(secKillInfoVo.getStartTime().getTime());
            skuItemVo.setEndTimeString(secKillInfoVo.getEndTime().getTime());
        }), poolExecutor);


        // 等待所有任务完成后返回数据
        try {
            CompletableFuture.allOf(imageFrture, attrGroupFrture, saleFutrue, descFutrue,killFutrue).get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }


        // 5. spu规格参数信息

        return skuItemVo;
    }

}